package com.cennavi.bigdata.baotou.util;


import com.alibaba.fastjson.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * @author 2810010108@qq.com
 * @packageName: com.zhuxl.exportdoc.util
 * @className: WordGeneratorUtils
 * @description: 文档生成工具类
 * @createTime: 2018/6/13 9:54 with idea 2018.1
 * </p>
 * version: V1.0.0
 */
public class WordGeneratorUtils {
    private static Configuration configuration = null;
    private static Map<String, Template> allTemplates = null;


    private static class FreemarkerTemplate {
        public static final String POVERTY = "poverty";

    }

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(WordGeneratorUtils.class, "/freemarker/template");
        allTemplates = new HashMap();
        try {
            allTemplates.put(FreemarkerTemplate.POVERTY, configuration.getTemplate(FreemarkerTemplate.POVERTY + ".ftl"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private WordGeneratorUtils() {
        throw new AssertionError();
    }

    public static String createDoc(Map<String, String> dataMap) {
        try {
            String name = dataMap.get("title") + dataMap.get("date") + ".doc";
//            File f = new File("D:\\"+name);
            File f = new File("/data/files/"+name);
            Template t = allTemplates.get(dataMap.get("freemarker/template"));
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
            return name;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("生成word文档失败");
        }
    }

    public static Map<String, String> parseToMap(JSONObject request) {
        Map<String, String> datas = new HashMap(32);
        //主标题
        datas.put("title", request.getString("title"));
        datas.put("date", request.getString("date"));
        datas.put("watermark", request.getString("watermark"));
        //遍历设置报表
        String[] infos = request.getString("info").split(",");
        datas.put("freemarker/template", request.getString("type"));
        datas.put("title_1" ,request.getString("title_1"));
        datas.put("title_2" ,request.getString("title_2"));
        datas.put("title_3" ,request.getString("title_3"));
        datas.put("base64_1",request.getString("base64"));
        for (int i = 0; i < infos.length; i++) {
            datas.put("info_"+(i+1),infos[i]);
        }
        return datas;
    }
}
